//
//  StatusListViewModel.swift
//  Weibo
//
//  Created by 潇 on 15/12/31.
//  Copyright © 2015年 潇. All rights reserved.
//

import UIKit
import SVProgressHUD

class StatusListViewModel: NSObject {
    
    //since_id 是实现下拉刷新新的微博字段
    class func loadHomePageData(since_id:Int, max_id:Int, finished: (statuses: [Status]?) -> ()) {
        
        //get 请求
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"

        //发送请求
        //判断 token 是否为空
        guard let token = UserAccountViewModel().token else {
            print("token为空")
            SVProgressHUD.showInfoWithStatus("请重新登录")
            return
        }
        
        var parameters = ["access_token" : token]
        //判断 since_id 是否大于0
        if since_id > 0 {
            parameters["since_id"] = "\(since_id)"
        }
        if max_id > 0 {
            parameters["max_id"] = "\(max_id - 1)"
        }
        
        NetworkTools.sharedTools.requestJSONDict(.GET, urlString: urlString, parameters: parameters) { (dict, error) -> () in
            if error != nil {
                //请求失败
//                SVProgressHUD.showInfoWithStatus("你的网络出问题,请稍后再试")
                //执行失败的回调
                SVProgressHUD.showInfoWithStatus("网络不佳")
                finished(statuses: nil)
                return
            }
            //请求成功
            if let array = dict!["statuses"] as? [[String : AnyObject]] {
                //                    print(array)
                //TODO:便利数组中所有字典,进行字典转模型
                var list = [Status]()//实例化
                for item in array {
                    //                        print(item["text"])
                    let s = Status(dict: item)
                    list.append(s)
                }
//                self.statuses = list
//                //改变数据源
//                self.tableView.reloadData()
                //执行成功的回调
                finished(statuses: list)
            }
        }

    }
}
